<template>
    <div class="sys-container">
        <div class="top-content">
            <el-form label-width="110px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务数据库">
                            <el-select
                                size="mini"
                                clearable
                                v-model="databaseConfig.businessDatabase"
                                @change="getDadaBaseConfig"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="(value, key) in businessDatabaseData"
                                    :value="key"
                                    :key="key"
                                    :label="key + ' ' + value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="数据库类型">
                            <el-select size="mini" v-model="databaseConfig.dbType" clearable style="width: 100%">
                                <el-option v-for="(value, key) in databaseTypeData" :value="key" :key="key" :label="key + ' ' + value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="连接地址">
                    <el-input size="mini" placeholder="请输入连接地址" v-model.trim="databaseConfig.jdbcUrl" clearable />
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="连接账号">
                            <el-input
                                type="text"
                                size="mini"
                                autocomplete="off"
                                v-model.trim="databaseConfig.userName"
                                placeholder="请输入连接账号"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="连接密码">
                            <el-input
                                size="mini"
                                autocomplete="new-password"
                                show-password
                                :disabled="disabledState"
                                v-model.trim="databaseConfig.passWord"
                                placeholder="请输入连接密码"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-button style="float: right" size="mini" type="primary" @click="handleTestConnect">测试连接</el-button>
        </div>
        <div class="middle-content">
            <div class="execute-content">
                <el-input type="textarea" resize="none" :rows="9" placeholder="请输入SQL" v-model="databaseConfig.sql"> </el-input>
            </div>
            <div class="operate">
                <el-button size="mini" type="primary" @click="confirm">执行</el-button>
                <el-button size="mini" type="primary" @click="handleExport">导出数据</el-button>
            </div>
        </div>
        <div class="bottom-content">
            <div v-if="showType" class="result-table">
                <RiskTable :key="tableKey" v-loading="tableLoading" :msg="resultMsg" :symbol="true" @getList="queryExecuteResult" />
            </div>
            <div v-else class="result-msg">
                <el-input readonly type="textarea" resize="none" :rows="11" v-model="executeMsg"> </el-input>
            </div>
        </div>
    </div>
</template>
<script lang="ts">
import RiskTable from '@/common/components/risk-table.vue';
import { downLoadFile } from '@/utils/request';
import { Component, Vue } from 'vue-property-decorator';

@Component({
    name: 'SystemOperations',
    components: {
        RiskTable,
    },
})
export default class SystemOperations extends Vue {
    // 业务数据库数据
    businessDatabaseData: any = {
        '1': '风控数据库',
        '2': '恒生数据库',
        '3': '聚源数据库',
        '4': '财汇数据库',
    };
    // 数据库类型数据
    databaseTypeData: any = {
        '1': 'oracle',
        '2': 'mysql',
    };

    // 数据库连接配置
    databaseConfig = {
        businessDatabase: '', // 业务数据库
        dbType: '', // 数据库类型
        jdbcUrl: '', // 连接地址
        userName: '', // 账号
        passWord: '', // 密码
        sql: '',
    };
    sqlContent: string = ''; // sql语句
    showType: boolean = true;
    tableColumns: any[] = []; // 执行结果表格列
    tableData: any[] = []; // 执行结果表数据
    executeMsg: string = ''; // 执行结果信息

    resultMsg: any = {
        returnData: { data: [], total: 0 },
        dataKey: 'data',
        title: [],
        height: '100%',
        hidePage: false,
        checked: { on: false, option: false },
    };

    tableKey: number = 0;
    pages: any = { pageSize: 10, currentPage: 1 };
    tableLoading: boolean = false;
    disabledState: boolean = false;

    // 获取数据库配置
    getDadaBaseConfig(val: any) {
        if (val) {
            this.$axios
                .get('/product/queryDataBaseConfiguration?businessDatabase=' + this.databaseConfig.businessDatabase)
                .then((res: any) => {
                    this.disabledState = true;
                    if (res) {
                        for (const key in res) {
                            this.databaseConfig[key] = res[key];
                        }
                    }
                })
                .catch(() => {
                    this.disabledState = false;
                    this.databaseConfig.dbType = '';
                    this.databaseConfig.jdbcUrl = '';
                    this.databaseConfig.userName = '';
                    this.databaseConfig.passWord = '';
                });
        } else {
            this.disabledState = false;
        }
    }

    // 校验表单参数
    handleVerifyParam() {
        let verifyParam = {
            // businessDatabase: '业务数据库',
            dbType: '数据库类型',
            jdbcUrl: '连接地址',
            userName: '连接账号',
            passWord: '连接密码',
        };
        for (const key in verifyParam) {
            if (!this.databaseConfig[key]) {
                this.yh_message_warn(verifyParam[key] + '不可为空');
                return false;
            }
        }
        return true;
    }

    // 测试连接
    handleTestConnect() {
        let verify = this.handleVerifyParam();
        if (!verify) return;
        this.$axios
            .post('/product/testConnection', this.databaseConfig)
            .then(res => {
                this.yh_message_success('连接成功');
            })
            .catch(err => {
                this.yh_message_error(err);
            });
    }

    queryExecuteResult(pages: any) {
        this.pages.pageSize = pages.pageSize;
        this.pages.currentPage = pages.currentPage;
        this.handleExecuteSQL('2');
    }

    confirm() {
        if (
            this.databaseConfig.sql.toUpperCase().indexOf('INSERT') > -1 ||
            this.databaseConfig.sql.toUpperCase().indexOf('UPDATE') > -1 ||
            this.databaseConfig.sql.toUpperCase().indexOf('DELETE') > -1
        ) {
            this.$confirm('当前操作影响数据安全,可能会造成系统事故,请确认！', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                closeOnClickModal: false,
                closeOnPressEscape: false,
            })
                .then(() => {
                    this.handleExecuteSQL('1');
                })
                .catch(() => {
                    // this.$message({
                    //     type: 'info',
                    //     message: '已取消删除',
                    // });
                });
        } else {
            this.handleExecuteSQL('1');
        }
    }

    /**
     * @Param type 1:执行 2：分页查询
     */
    handleExecuteSQL(type: string) {
        let verify = this.handleVerifyParam();
        if (!verify) return;

        if (!this.databaseConfig.sql) {
            this.yh_message_warn('请输入SQL语句！');
            return false;
        }
        let reg = /[;；]+/;
        let isRex = reg.test(this.databaseConfig.sql);
        if (isRex) {
            this.yh_message_warn('不支持;，请重新输入！');
            return false;
        }

        this.tableLoading = true;
        this.$axios
            .post('/product/executeSql', {
                ...this.databaseConfig,
                paging: this.pages,
            })
            .then((res: any) => {
                this.executeMsg = '';
                if (res && res.list && res.list.length) {
                    let data = res.list[0];
                    let title = Object.keys(data);
                    this.resultMsg.title = title.map(ele => {
                        return { name: ele, val: ele, minWidth: '180' };
                    });
                    this.resultMsg.returnData.data = res.list;
                    this.resultMsg.returnData.total = res.total;
                    this.showType = true;
                } else {
                    this.showType = false;
                    this.executeMsg = res;
                }
                this.tableLoading = false;
                if (type == '1') {
                    this.tableKey++;
                    this.yh_message_success('执行成功');
                }
            })
            .catch(err => {
                this.tableLoading = false;
                this.showType = false;
                this.executeMsg = err;
                // this.yh_message_error(err);
            });
    }

    // 导出数据
    handleExport() {
        if (!this.databaseConfig.sql) {
            this.yh_message_warn('请输入SQL语句！');
            return false;
        }
        let verify = this.handleVerifyParam();
        if (!verify) return;

        downLoadFile({
            url: '/product/exportResults',
            method: 'post',
            data: {
                ...this.databaseConfig,
                paging: {
                    pageSize: this.resultMsg.returnData.total,
                    currentPage: 1,
                },
            },
            loading: true,
            loadingMsg: '正在准备导出，请稍后··· ···',
        });
    }
}
</script>
<style lang="scss" scoped>
.sys-container {
    padding: 15px;
    height: 100%;
    width: 100%;
    .top-content {
        height: 24vh;
        min-height: 180px;
        border: 1px solid #d7d7d7;
        padding: 5px 15px;
        .el-form-item {
            margin-bottom: 5px;
        }
        /deep/.el-form-item__label {
            color: black;
        }
    }
    .middle-content,
    .bottom-content {
        margin-top: 10px;
        height: 35vh;
        min-height: 270px;
        border: 1px solid #d7d7d7;
        padding: 10px 15px;
    }
    .execute-content {
        height: calc(100% - 35px);
    }
    .operate {
        float: right;
    }
    .result-table {
        height: calc(100% - 10px);
    }
}
/deep/.el-pagination {
    padding: 15px 0px 15px 0px !important;
}
</style>
